package com.android.scanner.barcode;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Timer;
import java.util.TimerTask;

import com.android.scanner.R;
import com.android.scanner.utils.Constant;

import android.serialport.SerialPort;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TextView.OnEditorActionListener;

public class ScannerEngine {
	/** Called when the activity is first created. */

	public static final int KEY_SCAN = 111;
	public static final int KEY_F1 = 112;
	public static final int KEY_F2 = 113;
	public static final int KEY_F3 = 114;
	public static final int KEY_F4 = 115;
	private int KEY_POSITION = 0;

	private DeviceControl DevCtrl;
	private SerialPort mSerialPort;
	private String str = new String();
	private String buff = new String();
	public int fd;
	private ReadThread mReadThread;
	private Handler mHandler = null;
	private static final String TAG = "SerialPort";
	private boolean key_start = true;
	private boolean Powered = false;
	private boolean Opened = false;
	private Timer timer = new Timer();
	private Timer retrig_timer = new Timer();
	private SoundPool soundPool;
	private int soundId;
	private Handler t_handler = null;
	private Handler n_handler = null;
	Handler handler = null;
	private boolean ops = false;

	private Context mContext;

	public ScannerEngine(Context context, Handler handler1) {
		mHandler = handler1;
		mContext = context;
		
	}

	public void init() {
		try {
			DevCtrl = new DeviceControl("/proc/driver/scan");

		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IOException e) {
			Log.d(TAG, "AAA");
			handler.sendEmptyMessage(Constant.SCAN_ERROR);
			return;
		}
		ops = true;

		soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
		soundId = soundPool.load("/system/media/audio/ui/VideoRecord.ogg", 0);

		t_handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				if (msg.what == 1) {
					try {
						DevCtrl.PowerOffDevice();
					} catch (IOException e) {
						Log.d(TAG, "BBB");
						// TODO Auto-generated catch block
						e.printStackTrace();
					}// powersave
					Powered = false;
				}
			}
		};

		n_handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				if (msg.what == 1) {
					try {
						if (key_start == false) {
							DevCtrl.TriggerOffDevice();
							timer = new Timer(); // start a timer, when machine
													// is idle for some time,
													// cut off power to save
													// energy.
							timer.schedule(new MyTask(), 60000);
							key_start = true;
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		};

		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				if (msg.what == 1) {
					soundPool.play(soundId, 1, 1, 0, 0, 1);
					key_start = true;
					retrig_timer.cancel();
				}
			}
		};
	}

	class MyTask extends TimerTask {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			Message message = new Message();
			message.what = 1;
			t_handler.sendMessage(message);
		}
	}

	class RetrigTask extends TimerTask {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			Message message = new Message();
			message.what = 1;
			n_handler.sendMessage(message);
		}
	}

	public void stop() {
		// TODO Auto-generated method stub
		if (ops == true) {
			mReadThread.interrupt();
			timer.cancel();
			retrig_timer.cancel();
			try {
				DevCtrl.PowerOffDevice();
				Thread.sleep(1000);
			} catch (IOException e) {
				Log.d(TAG, "CCC");
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Powered = false;
			if (Opened == true) {
				mSerialPort.CloseSerial(fd);
				Opened = false;
			}
		}
	}

	public void start() {
		// TODO Auto-generated method stub
		if (ops == true) {
			if (Opened == false) {
				try {
					// mSerialPort = new SerialPort("/dev/eser1",9600);//3a
					mSerialPort = new SerialPort();// ("/dev/eser0",9600);//35
					mSerialPort.OpenSerial("/dev/eser0", 9600);
				} catch (SecurityException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					Log.d(TAG, "DDD");
					// TODO Auto-generated catch block
					e.printStackTrace();
					mHandler.sendEmptyMessage(Constant.SCAN_ERROR);
					ops = false;
					soundPool.release();
					try {
						DevCtrl.DeviceClose();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					return;
				}
				fd = mSerialPort.getFd();
				if (fd > 0) {
					Log.d(TAG, "opened");
					Opened = true;
				}
			}
			mReadThread = new ReadThread();
			mReadThread.start();
		}
		Log.d(TAG, "onResume");
	}

	public void close() {
		// TODO Auto-generated method stub
		if (ops == true) {
			try {
				soundPool.release();
				DevCtrl.DeviceClose();
			} catch (IOException e) {
				Log.d(TAG, "EEE");
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public boolean scan() {
		try {
			if (Powered == false) {
				Powered = true;
				DevCtrl.PowerOnDevice();
			}
			timer.cancel();
			DevCtrl.TriggerOnDevice();
			key_start = false;
			retrig_timer = new Timer();
			retrig_timer.schedule(new RetrigTask(), 3500); // start a timer, if
															// the data is not
															// received within a
															// period of time,
															// stop the scan.
			return true;
		} catch (IOException e) {
			Log.d(TAG, "FFF");
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	private class ReadThread extends Thread {

		@Override
		public void run() {
			super.run();
			while (!isInterrupted()) {
				try {
					Log.d(TAG, "read");
					buff = mSerialPort.ReadSerialString(fd, 1024);
					Log.d(TAG, "end");
					if (buff != null) {
						System.out.println("result:" + buff);
						Message msg = new Message();
						msg.what = 1;
						handler.sendMessage(msg);
						Message msgRst = Message.obtain();
						msgRst.what = Constant.SCAN_FINISH;
						Bundle b = new Bundle();
						b.putString("rst", buff);
						msgRst.setData(b);
						mHandler.sendMessage(msgRst);
						timer = new Timer();
						timer.schedule(new MyTask(), 60000);
					} else {
						Message msg = new Message();
						msg.what = 0;
						handler.sendMessage(msg);
						Message msgRst = Message.obtain();
						msgRst.what = Constant.SCAN_FINISH;
						mHandler.sendMessage(msgRst);
					}
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
